package com.abc.jpatest.bean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.persistence.*;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import lombok.*;

@EqualsAndHashCode
@Getter
@Setter
@RequiredArgsConstructor
@Entity
@Table(name = "tb_department")
public class Department {
    @Id
    private Long department_id;
    private String department_name;

    @OneToMany(
        targetEntity = Employee.class, 
        // fetch = FetchType.LAZY,
        fetch = FetchType.EAGER, 
        // cascade = CascadeType.PERSIST,
        orphanRemoval = true)
    @JoinColumn(name = "department_id")
    private List<Employee> employees = new ArrayList<>();

    // 级联输出employees史会导致栈溢出，要重写toString()方法。
    @Override
    public String toString() {

        StringBuffer emps = new StringBuffer();
        Iterator<Employee> iterator = employees.iterator();
        while (iterator.hasNext()) {
            emps.append(iterator.next().getId() + " ");
        }

        return "Department [department_id=" + department_id + ", department_name=" + department_name + ", employees="
                + emps + "]";
    }

}
